/*------------------------------------------------------------------------------
 * Tiger: The primary copyright protection functions.
------------------------------------------------------------------------------*/
#define	_IN_TIGER_CIPHER
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <android/log.h>

/*****************************************************************************/
static void tiger_encipher (
				  unsigned long *const        v,
				  const unsigned long *const  k,
				  unsigned long *const        w) 
{
	register unsigned long 
		y     = ntohl(v[0]),
		z     = ntohl(v[1]),
		a     = ntohl(k[0]),
		b     = ntohl(k[1]),
		c     = ntohl(k[2]),
		d     = ntohl(k[3]),
		n     = 0x10,
		sum   = 0,
		delta = 0x9E3779B9; /*  0x9E3779B9 - 0x100000000 = -0x61C88647 */
	
	while (n-- > 0) {
		sum += delta;
		y += ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
		z += ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
	}// while
	
	w[0] = htonl(y); w[1] = htonl(z);
}// tiger_encipher

/*****************************************************************************/
static void tiger_decipher(
				 unsigned long *const        v,
				 const unsigned long *const  k,
				 unsigned long *const        w)
{
	register unsigned long
		y     = ntohl(v[0]),
		z     = ntohl(v[1]),
		a     = ntohl(k[0]),
		b     = ntohl(k[1]),
		c     = ntohl(k[2]),
		d     = ntohl(k[3]),
		n     = 0x10,
		sum   = 0xE3779B90, // why this ? must be related with n value
		delta = 0x9E3779B9;
	
	/* sum = delta<<5, in general sum = delta * n */
	while (n-- > 0) {
		z -= ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
		y -= ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
		sum -= delta;
	}
	
	w[0] = htonl(y); w[1] = htonl(z);
}// tiger_decipher

static unsigned long next = 1;
           
/* RAND_MAX assumed to be 32767 */
static int my_rand(void) {
	next = next * 1103515245 + 12345;
	return((unsigned)(next/65536) % 32768);
}

/********************************************************************
 * encrypt part
 *******************************************************************/
static void tiger_encrypt (  
				 unsigned char*  instr,
				 int             instrlen,
				 unsigned char*  key,
				 unsigned char*  outstr,
				 int*            outstrlen_prt)
{
	unsigned char 
		plain[8],         // plain text buffer
		plain_pre_8[8],   // plain text buffer, previous 8 bytes
		* crypted,        // crypted text
		* crypted_pre_8,  // crypted test, previous 8 bytes
		* inp;            // current position in instr
	int 
		pos_in_byte = 1,  // loop in the byte 
		is_header=1,      // header is one byte
		count=0,          // number of bytes being crypted
		padding = 0;      // number of padding stuff
	
//	int my_rand(void) {    // it can be the real random seed function
//		return 0xdead; }  // override with number, convenient for debug
	
	pos_in_byte = (instrlen + 0x0a) % 8; // header padding decided by instrlen
	if (pos_in_byte) { 
		pos_in_byte = 8 - pos_in_byte; 
	}
	plain[0] = (my_rand() & 0xf8) | pos_in_byte;
	
	memset(plain+1, (int)(my_rand()&0xff), pos_in_byte++);
	memset(plain_pre_8, (int)0x00, sizeof(plain_pre_8));
	
	crypted = crypted_pre_8 = outstr;
	
	padding = 1; // pad some stuff in header
	while (padding <= 2) { // at most two byte 
		if(pos_in_byte < 8) { plain[pos_in_byte++] = my_rand() & 0xff; padding ++; } 
		if(pos_in_byte == 8){ {
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			if(is_header) { plain[pos_in_byte] ^= plain_pre_8[pos_in_byte]; }
			else { plain[pos_in_byte] ^= crypted_pre_8[pos_in_byte]; }
		}
	// prepare plain text	/*** we encrypt every eight byte ***/
		tiger_encipher( (unsigned long *) plain,
			(unsigned long *) key, 
			(unsigned long *) crypted);   // encrypt it
		
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			crypted[pos_in_byte] ^= plain_pre_8[pos_in_byte]; 
		} 
		memcpy(plain_pre_8, plain, 8);     // prepare next
		
		crypted_pre_8   =   crypted;       // store position of previous 8 byte
		crypted         +=  8;             // prepare next output
		count           +=  8;             // outstrlen increase by 8
		pos_in_byte     =   0;             // back to start
		is_header       =   0;             // and exit header
	} } 
	}
	
	inp = instr;
	while (instrlen > 0) {
		if (pos_in_byte < 8) { plain[pos_in_byte++] = *(inp++); instrlen --; }
		if (pos_in_byte == 8){ {
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			if(is_header) { plain[pos_in_byte] ^= plain_pre_8[pos_in_byte]; }
			else { plain[pos_in_byte] ^= crypted_pre_8[pos_in_byte]; }
		}
	// prepare plain text	/*** we encrypt every eight byte ***/
		tiger_encipher( (unsigned long *) plain,
			(unsigned long *) key, 
			(unsigned long *) crypted);   // encrypt it
		
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			crypted[pos_in_byte] ^= plain_pre_8[pos_in_byte]; 
		} 
		memcpy(plain_pre_8, plain, 8);     // prepare next
		
		crypted_pre_8   =   crypted;       // store position of previous 8 byte
		crypted         +=  8;             // prepare next output
		count           +=  8;             // outstrlen increase by 8
		pos_in_byte     =   0;             // back to start
		is_header       =   0;             // and exit header
	} }
	}
	
	padding = 1; // pad some stuff in tailer
	while (padding <= 7) { // at most sever byte
		if (pos_in_byte < 8) { plain[pos_in_byte++] = 0x00; padding ++; }
		if (pos_in_byte == 8){ {
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			if(is_header) { plain[pos_in_byte] ^= plain_pre_8[pos_in_byte]; }
			else { plain[pos_in_byte] ^= crypted_pre_8[pos_in_byte]; }
		}
	// prepare plain text	/*** we encrypt every eight byte ***/
		tiger_encipher( (unsigned long *) plain,
			(unsigned long *) key, 
			(unsigned long *) crypted);   // encrypt it
		
		for(pos_in_byte=0; pos_in_byte<8; pos_in_byte++) {
			crypted[pos_in_byte] ^= plain_pre_8[pos_in_byte]; 
		} 
		memcpy(plain_pre_8, plain, 8);     // prepare next
		
		crypted_pre_8   =   crypted;       // store position of previous 8 byte
		crypted         +=  8;             // prepare next output
		count           +=  8;             // outstrlen increase by 8
		pos_in_byte     =   0;             // back to start
		is_header       =   0;             // and exit header
	} }
	} 
	
	*outstrlen_prt = count;
}// tiger_encrypt

/******************************************************************** 
 * [decrypt part]
 * return 0 if failed, otherwise return 1
 ********************************************************************/
static int tiger_decrypt (
				unsigned char*  instr,
				int             instrlen,
				unsigned char*  key,
				unsigned char*  outstr,
				int*            outstrlen_ptr)
{
	unsigned char 
		decrypted[8], m[8],
		* crypt_buff, 
		* crypt_buff_pre_8, 
		* outp;
	int 
		count, 
		context_start, 
		pos_in_byte, 
		padding;
	
	// at least 16 bytes and %8 == 0
	if ((instrlen % 8) || (instrlen < 16)) return 0; 
	// get information from header
	tiger_decipher( (unsigned long *) instr, 
		(unsigned long *) key, 
		(unsigned long *) decrypted);
	pos_in_byte = decrypted[0] & 0x7;
	count = instrlen - pos_in_byte - 10; // this is the plaintext length
	// return if outstr buffer is not large enought or error plaintext length
	if (*outstrlen_ptr < count || count < 0) return 0;
	
	memset(m, 0, 8);
	crypt_buff_pre_8 = m;
	*outstrlen_ptr = count;   // everything is ok! set return string length
	
	crypt_buff = instr + 8;   // address of real data start 
	context_start = 8;        // context is at the second 8 byte
	pos_in_byte ++;           // start of paddng stuff
	
	padding = 1;              // at least one in header
	while (padding <= 2) {    // there are 2 byte padding stuff in header
		if (pos_in_byte < 8) {  // bypass the padding stuff, none sense data
			pos_in_byte ++; padding ++;
		}
		if (pos_in_byte == 8) {
			crypt_buff_pre_8 = instr;
			{
		for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte ++ ) {
			if (context_start + pos_in_byte >= instrlen) return 1;
			decrypted[pos_in_byte] ^= crypt_buff[pos_in_byte];
		}
		tiger_decipher( (unsigned long *) decrypted, 
			(unsigned long *) key, 
			(unsigned long *) decrypted);
		
		context_start +=  8;
		crypt_buff    +=  8;
		pos_in_byte   =   0;
	} 
		}
	}// while
	
	outp = outstr;
	while(count !=0) {
		if (pos_in_byte < 8) {
			*outp = crypt_buff_pre_8[pos_in_byte] ^ decrypted[pos_in_byte];
			outp ++;
			count --;
			pos_in_byte ++;
		}
		if (pos_in_byte == 8) {
			crypt_buff_pre_8 = crypt_buff - 8;
			{
		for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte ++ ) {
			if (context_start + pos_in_byte >= instrlen) return 1;
			decrypted[pos_in_byte] ^= crypt_buff[pos_in_byte];
		}
		tiger_decipher( (unsigned long *) decrypted, 
			(unsigned long *) key, 
			(unsigned long *) decrypted);
		
		context_start +=  8;
		crypt_buff    +=  8;
		pos_in_byte   =   0;
	}
		}
	}// while
	
	for (padding = 1; padding < 8; padding ++) {
		if (pos_in_byte < 8) {
			if (crypt_buff_pre_8[pos_in_byte] ^ decrypted[pos_in_byte]) return 0;
			pos_in_byte ++; 
		}
		if (pos_in_byte == 8 ) {
			crypt_buff_pre_8 = crypt_buff;
			{
		for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte ++ ) {
			if (context_start + pos_in_byte >= instrlen) return 1;
			decrypted[pos_in_byte] ^= crypt_buff[pos_in_byte];
		}
		tiger_decipher( (unsigned long *) decrypted, 
			(unsigned long *) key, 
			(unsigned long *) decrypted);
		
		context_start +=  8;
		crypt_buff    +=  8;
		pos_in_byte   =   0;
	} 
		}
	}// for
	return 1;
}// tiger_decrypt

/*****************************************************************************/
/* This is the Public Function */
// return 1 is succeed, otherwise return 0
static int tiger_crypt (
			  unsigned char   flag,
			  unsigned char*  instr,
			  int             instrlen,
			  unsigned char*  key,
			  unsigned char*  outstr,
			  int*            outstrlen_ptr)
{
	if (flag == 0)
		return tiger_decrypt(instr, instrlen, key, outstr, outstrlen_ptr);
	else if (flag == 1)
		tiger_encrypt(instr, instrlen, key, outstr, outstrlen_ptr);
	
	return 1; // flag must be DECRYPT or ENCRYPT
}// tiger_crypt
/*****************************************************************************/
// END of crypt

#if 0
int mobot_encrypt(
			  unsigned char*  instr,
			  int             instrlen,
			  unsigned char*  key,
			  unsigned char*  outstr,
			  int*            outstrlen_ptr)
{
	return(tiger_crypt(1, instr, instrlen, key, outstr, outstrlen_ptr));
}
#endif

int mobot_decrypt(
			  unsigned char*  instr,
			  int             instrlen,
			  unsigned char*  key,
			  unsigned char*  outstr,
			  int*            outstrlen_ptr)
{
	outstr[0] = 0xe0;
	int ret = tiger_crypt(0, instr, instrlen, key, outstr, outstrlen_ptr);
	if(ret <= 0) return -1;
	return ret;
}

#define	MAGIC_RANDOM_SEED	0x080919

char mobotSn[64];

void _get_dpf_sn(unsigned char *mac_str, char *dpf_sn)
{
	unsigned char mask_byte[6];
	char buf[3];
	int index = mac_str[5] % 10;

	dpf_sn[0] = '\0';

//	srand(MAGIC_RANDOM_SEED);
	next = 1992111;
	int i;
	for(i=0; i<index; i++)
		my_rand();
	sprintf(dpf_sn, "%02X", index);

	printf("mask_bytes: ");
	for(i=0; i<6; i++)
	{
		mask_byte[i] = (unsigned char )((unsigned int)my_rand() % 256);
		//printf("%02X ", mask_byte[i]);
		__android_log_print(ANDROID_LOG_DEBUG, "honey-TEST",
	  "auth mask_byte:%02X", mask_byte[i]);
		sprintf(buf, "%02X", mask_byte[i]^mac_str[i]);
		strcat(dpf_sn, buf);
	}
	//printf("\n");
	__android_log_print(ANDROID_LOG_DEBUG, "honey-TEST",
	  "auth dpfsn:%s", dpf_sn);
	  __android_log_print(ANDROID_LOG_DEBUG, "honey-TEST",
	  "auth mobotSn:%s", mobotSn);

}

void get_dpf_sn(char *mac_str)
{
	__android_log_print(ANDROID_LOG_DEBUG, "honey-TEST",
	  "auth mac = %s",
	  mac_str);
	if(mac_str == NULL || strlen(mac_str) < 17) // Not avaliable
		return;
	unsigned char mac[6];
	int i=0;
	char *pt = mac_str;
	char *endptr;
	for(i=0; i<6; i++)
	{
		char tmpstr[10];
		strncpy(tmpstr, pt, 2);
		tmpstr[2] = '\0';
		mac[i] = (unsigned char)strtol(tmpstr, &endptr, 16);
		pt = pt+3;
	}

	__android_log_print(ANDROID_LOG_DEBUG, "honey-TEST",
	  "auth mac NB = %02X %02X %02X %02X %02X %02X",
	  mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

	_get_dpf_sn(mac, mobotSn);
}

int authProc(char *mac, char *authStr)
{
	unsigned char result[64];
	int result_len = 64, i;
	
	get_dpf_sn(mac);
		
	char tmpstr[3], *endptr;
	unsigned char inStr[100];
	char *ptr = (char *)authStr;
	if(ptr == NULL) return 0;
	
	int len = strlen(ptr);
	for(i=0; i<len/2; i++)
	{
		strncpy(tmpstr, ptr+(i*2), 2);
		tmpstr[2] = '\0';
		inStr[i] = (unsigned char)strtoul(tmpstr, &endptr, 16);
	}
	
	int ret = mobot_decrypt(inStr, len/2, (unsigned char *)mobotSn, result, &result_len);
	if(ret == -1) return 0;
	
	if(result[0] != 0x08 || result[1] != 0x20 || result[2] != 0x09 || result[3] != 0x19)
		return 0;
	return 1;
}

